<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Feedback extends Controller_Common {

	public $template='layout/index';

	public function emptyPost() {
		return array(
			'name' => '',
			'email' => '',
			'phone' => '',
			'content' => ''
		);
	}

	public function action_index() {
		$this->buildCarcas();

		$this->template->content = View::factory('pages/contactsPage', array(
			'post' => $this->emptyPost()
		));
	}

	public function action_send() {
		$this->buildCarcas();
		$post = Validation::factory($_POST); // валидируем данные с формы

		$post->rule('name', 'not_empty')
			->rule('email', 'not_empty')->rule('email', 'email_domain')
			->rule('phone', 'phone');

		if ($post->check()) {
			try {
				$subscriber = ORM::factory('Subscribers');
				$subscriber->name = $this->request->post('name');
				$subscriber->email = $this->request->post('email');
				$subscriber->type = 1;
				$subscriber->save();
			} catch (Exception $e) {
				
			}

	        $config = Kohana::$config->load('email');
	        Email::connect($config);

	        $from = 'zeller.kz@gmail.com';
	        $to = Kohana::$config->load('main')->feedback_mail;
	        $subject = 'С нами хочет связаться '.$this->request->post('email');
	        $message = '
	        	<div>От кого: <a href="mailto:'.$this->request->post('email').'">'.$this->request->post('email').'</a></div>
	        	<div>Имя или название компании: '.$this->request->post('name').'</div>
	        	<div>Телефон: '.$this->request->post('phone').'</div>
	        	<div>Сообщение:</div>
	        	<div>'.nl2br($this->request->post('content')).'</div>
	        ';

	        Email::send($to, $from, $subject, $message, $html = true);

			$this->template->content = View::factory('pages/message', array(
				'message' => 'Спасибо, ваше сообщение было отправлено.'
			));
		} else {
			$this->template->content = View::factory('pages/contactsPage', array(
				'errors' => $post->errors(),
				'post' => $_POST
			));
		}
	}

}